
from pynput.mouse import Button
from pynput import mouse
import time
import pyautogui
import json
import asyncio


class Recorder:
    
    def __init__(self, out=print):
        self.hold = []
        self.action = []
        self.out = out
    
    async def run(self):

        def on_click(x, y, button, pressed):
            if pressed:
                self.hold = [x, y, time.time()]
            else:  
                if x == 0 or y == 0:
                    return False
                self.action.append([self.hold[0], self.hold[1], self.hold[2], x, y, time.time()])
        
        with mouse.Listener(on_click=on_click) as listener:
            listener.join()

        for i in range(len(self.action)):
            j = len(self.action) - i - 1
            self.action[j][5] -= self.action[j][2]
            if j==0:
                self.action[j][2] = 0
            else:
                self.action[j][2] -= self.action[j-1][5]

        f = open("./data/action.json", "w")
        f.write (json.dumps(self.action))
        f.close()

class Player:

    def __init__(self, out=print):

        self.action = None
        self.out = out

    async def run(self, noDelay=False):

        f = open("./data/action.json", "r")
        self.action = json.loads(f.read())

        if noDelay:
            print('低延迟模式')

        for act in self.action:
            await asyncio.sleep(0.4)
            # if noDelay:
            #     await asyncio.sleep(0.2)
            # else:
            #     await asyncio.sleep(act[2])
            pyautogui.click(x=act[0], y=act[1])

    async def moveToFirst(self):

        f = open("./data/action.json", "r")
        self.action = json.loads(f.read())

        if len(self.action) == 0:
            return
        
        act = self.action[0]

        pyautogui.moveTo(x=act[0], y=act[1])

        


# Recorder().run()

# Player().run()
